<?php

namespace App\Models\Customer;

use App\Models\BaseModel;
use Illuminate\Support\Facades\Auth;

class Family extends BaseModel
{

    protected $table = 'families';
    protected $fillable = [
        'code', 'remark', 'state', 'created_by', 'updated_by', 'data_scope',
    ];
    public $sorters = [];
    public $params = [
        'code', 'member_code', 'title', 'title_amend', 'contact', 'contact_phone', 'doctor', 'customer', 'created_by',
        'start_date', 'end_date'
    ];

    public function members()
    {
        return $this->hasMany('App\Models\Customer\FamilyMember', 'family_id');
    }

    public function createdBy()
    {
        return $this->belongsTo('App\Models\Account\User', 'created_by');
    }

    /**
     * 添加家系
     * @param $data
     * @return mixed
     */
    public function addFamily($data)
    {
        $code = $this->orderBy('code', 'desc')->limit(1)->first(['code']);

        if ($code) {
            $data['code'] = 'NJ' . str_pad(substr($code->code, 2) + 1, 6, 0, STR_PAD_LEFT);
        } else {
            $data['code'] = 'NJ000001';
        }

        $userId = Auth::id();
        $data['created_by'] = $userId;
        $data['updated_by'] = $userId;
        $data['data_scope'] = $this->getDataScope();

        return $this->create($data);
    }

    /**
     * 编辑家系
     * @param $data
     * @param $id
     * @return null
     */
    public function editFamily($data, $id)
    {
        $model = $this->find($id);

        if (!$model) {
            return null;
        }

        $data['updated_by'] = Auth::id();

        return $model->updateOrCreate(['id' => $id], $data);
    }

    /**
     * 获取家系列表
     * @param $limit
     * @param $sorter
     * @param $search
     * @param $defaultSorter
     * @return mixed
     */
    public function getFamilyList($limit, $sorter, $search, $defaultSorter)
    {
        $perPage = $limit > 0 ? $limit : $this->limit;
        if ($defaultSorter == 'desc') {
            $model = $this->orderBy('created_at', $defaultSorter);
        } else {
            $model = $this->orderBy($sorter[0], $sorter[1]);
        }

        $model->select(['id', 'code', 'remark', 'created_by', 'created_at', 'updated_at', 'state'])
            ->with([
                'members' => function ($member) {
                    $member->where('relation', 'X')->select([
                        'family_id', 'code', 'title', 'title_amend'
                    ]);
                },
                'createdBy:id,username'
            ]);

        foreach ($search as $key => $value) {
            switch ($key) {
                case 'code':
                    $model->where('code', 'like', '%' . $value . '%');
                    break;
                case 'created_by':
                    $model->whereHas('members.createdBy', function ($create) use ($value) {
                        $create->where('username', 'like', '%' . $value . '%');
                    });
                    break;
                case 'member_code':
                    $model->whereHas('members', function ($members) use ($key, $value) {
                        $members->where('code', 'like', '%' . $value . '%');
                    });
                    break;
                case 'title':
                case 'title_amend':
                case 'contact':
                case 'contact_phone':
                    $model->whereHas('members', function ($members) use ($key, $value) {
                        $members->where($key, 'like', '%' . $value . '%');
                    });
                    break;
                case 'doctor':
                    $model->whereHas('members.doctor', function ($doctor) use ($value) {
                        $doctor->where('title', 'like', '%' . $value . '%');
                    });
                    break;
                case 'customer':
                    $model->whereHas('members.customer', function ($customer) use ($value) {
                        $customer->where('title', 'like', '%' . $value . '%');
                    });
                    break;
            }
        }

        if (!empty($search['start_date'])) {
            $model->where('created_at', '>=', $search['start_date']);
        }

        if (!empty($search['end_date'])) {
            $model->where('created_at', '<=', $search['end_date']);
        }

        $data = $model->paginate($perPage)->toArray();
        foreach ($data['data'] as $key => $value) {
            if (count($value['members']) > 0) {
                $data['data'][$key]['members'] = $value['members'][0];
            }
        }

        return $data;
    }

    /**
     * 获取指定家系下面所有成员信息
     * @param $id
     * @return \Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|null|static|static[]
     */
    public function getFamilyMemberAll($id)
    {
        $model = $this->with([
            'members:id,family_id,title,title_amend,code,gender,birthday,age,age_unit,age_range,age_range_unit,relation,birthplace,' .
            'address,wechat,contact,contact_phone,nation,is_patient,clinical_diagnosis,case_code,family_history,clinical_keyword,' .
            'first_date,identity_card,customer,department,doctor,created_by,created_at,updated_at',
            'members.customer:id,title',
            'members.department:id,title',
            'members.doctor:id,title',
            'members.createdBy:id,username',
            'members.relation:code,title',
            'members.isPatient:code,title'
        ])->find($id, ['id']);

        if (!$model) {
            return null;
        }

        return $model;
    }
}
